package com.hxzy.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.enums.AckCode;
import com.hxzy.dto.LoginDTO;
import com.hxzy.entity.Contamer;
import com.hxzy.exception.ServiceException;
import com.hxzy.mapper.ContamerMapper;
import com.hxzy.service.ContamerService;
import com.hxzy.vo.AccountVO;
import com.hxzy.vo.LoginVO;
import com.hxzy.vo.ReportVO;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 客户信息
 * @author Administrator
 */
@Service
public class ContamerServiceImpl extends ServiceImpl<ContamerMapper, Contamer> implements ContamerService {

    /**
     * 本月新注册的会员数
     * @return
     */
    @Override
    public long currentMonthRegister() {
        return super.getBaseMapper().currentMonthRegister();
    }

    /**
     * 范围(1 本周，2本月，3全年)
     * @param range
     * @return
     */
    @Override
    public List<ReportVO> contamerLineBar(int range) {
        List<ReportVO> arr=null;
        if(range==3){
            arr=this.getBaseMapper().fullYearContamerNum();
        }else if(range==1){
            //今天为准，向前同推6天
            arr=thisWeekContamerNum();
        }else{
            //本月
            arr=thisMonthContamerNum();
        }
        return arr;
    }

    /**
     * 前端用户登录
     * @param loginDTO
     * @return
     */
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        Contamer db = this.getBaseMapper().findByUserName(loginDTO.getLoginName());

        if(db==null){
            throw new ServiceException(AckCode.LOGIN_ACCOUNT_PASSWORD_ERROR);
        }

         if(!BCrypt.checkpw(loginDTO.getLoginPwd(), db.getPassword())){
             throw new ServiceException(AckCode.LOGIN_ACCOUNT_PASSWORD_ERROR);
         }

         if(db.getStatus()==1){
             throw new ServiceException(AckCode.DEVICE_BANNED);
         }

         LoginVO loginVO=new LoginVO();

        AccountVO  accountVO=new AccountVO();
        accountVO.setId(new Long(db.getId()));
        accountVO.setLoginName(db.getLoginName());
        accountVO.setName(db.getUserName());
        accountVO.setStatus(db.getStatus().byteValue());
        accountVO.setAvatar(db.getPortrait());
        accountVO.setGender(db.getGender().intValue());

        loginVO.setAccountVO(accountVO);
        return loginVO;
    }

    /**
     * 本月的会员注册量
     * @return
     */
    private List<ReportVO> thisMonthContamerNum() {

        List<ReportVO> newReportVOList = new ArrayList<>();
        //数据库的值
        List<ReportVO> reportVOS = this.baseMapper.thisMonthNumbers();
        //该月的第一天
        LocalDate beginDate = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
        //该月的最后一天
        //LocalDate endDate = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
        //今天
        LocalDate endDate = LocalDate.now();
        //计算两个日期相差的距离
        Period period = Period.between(beginDate, endDate);
        //计算相差的天数
        int days = period.getDays();
        //循环天数
        for (int i = 0; i <= days; i++) {
            LocalDate dt = beginDate.plusDays(i);
            //筛选
            Optional<ReportVO> first = reportVOS.stream().filter(p -> p.getLabel().equalsIgnoreCase(dt.toString())).findFirst();
            //实例化
            ReportVO<Long> vo = new ReportVO();
            vo.setLabel(dt.format(DateTimeFormatter.ofPattern("MM-dd")));

            if (first.isPresent()) {
                vo.setData((Long) first.get().getData());
            } else {
                vo.setData(0L);
            }
            newReportVOList.add(vo);
        }
        return newReportVOList;
    }


    /**
     * 本周的会员注册量
     * @return
     */
    private List<ReportVO> thisWeekContamerNum() {
        List<ReportVO> arr=new ArrayList<>();

        //数量里面可能一笔都没有,也有可能 没有完整7天
        List<ReportVO> db = this.getBaseMapper().thisWeekContamerNum();
        if(db.size()==7){
            return db;
        }else{
            //重新整理这7天的结果
            for(int i=6;i>=0;i--){
               String timeStr= LocalDate.now().minusDays(i).format(DateTimeFormatter.ofPattern("yyyy/MM/dd")).toString();
               //查看是否存在这个日期
                List<ReportVO> collect = db.stream().filter(p -> p.getLabel().equals(timeStr)).collect(Collectors.toList());

                ReportVO rvo=null;
                if(collect.size()>0){
                    rvo=collect.get(0);
                }else{
                    rvo=new ReportVO();
                    rvo.setData(0);
                    rvo.setLabel(timeStr);
                }
                arr.add(rvo);
            }
        }

        return arr;
    }
}
